var drecordArr;
var otherRes;
var datapicker_option = {
		showOtherMonths: true,
		selectOtherMonths: true,
		changeMonth: true,
		changeYear: true
};
jQuery(function($) {
	var grid_selector = "#grid-table";
	var pager_selector = "#grid-pager";
	//在动态加载css文件之前，先把前一个页面动态加载的css文件删除，动态加载的css文件的class='pageSpecCss'
	$("head link").remove(".pageSpecCss");

	// 由于子页面的css文件需要添加到主页面的固定地方，所以只能用js代码动态添加
	//$("#cssLink").after("<link rel='stylesheet' class='pageSpecCss' href='../assets/css/ui.jqgrid.css'></link>");

	// resize to fit page size
	$(window).on('resize.jqGrid', function() {
		$(grid_selector).jqGrid('setGridWidth', $(".page-content").width());
	});
	// resize on sidebar collapse/expand
	var parent_column = $(grid_selector).closest('[class*="col-"]');
	$(document).on(
			'settings.ace.jqGrid',
			function(ev, event_name, collapsed) {
				if (event_name === 'sidebar_collapsed'
						|| event_name === 'main_container_fixed') {
					$(grid_selector).jqGrid('setGridWidth',
							parent_column.width());
				}
			});
	$("#start,#end").datepicker(datapicker_option);	
	
	var height = $(window).height();
	height = height - 45 - 41 - 64;
	var hstr = height + 'px';
	$('#page-content').css('height',hstr);
	var gridhegith = 320;//= $('#page-content').height() - 380;
	$.ajax({
		type : "post",
		url : "../diagnose/getWindFarmList.do",
		dataType : "json",
		success : function(data){
			var farmOptionStr = "";
			var farmList = eval(data.resBody);
			for(var i=0; i<farmList.length; i++){
				if(i==0)
					farmOptionStr = "<option value='" + farmList[i].farmid + "' selected>" + farmList[i].farmname + "</option>";
				else
					farmOptionStr = farmOptionStr + "<option value='" + farmList[i].farmid + "'>" + farmList[i].farmname + "</option>";
			}
			$("#farmid").empty();
			$("#farmid").append(farmOptionStr);
			var farmid = $("#farmid option:selected").val();
			$.ajax({
				type : "post",
				url : "../diagnose/getTurbineList.do",
				dataType : "json",
				data : {farmid:farmid},
				success : function(data){
					var turbineOptionStr = "";
					var turbineList = eval(data.resBody);
					for(var i=0; i<turbineList.length; i++){
						if(i==0)
							turbineOptionStr = "<option value='" + turbineList[i] + "' selected>" + turbineList[i] + "</option>";
						else
							turbineOptionStr = turbineOptionStr + "<option value='" + turbineList[i] + "'>" + turbineList[i] + "</option>";
					}
					$("#turbine").empty();
					$("#turbine").append(turbineOptionStr);
				}
			});
			$("#farmid").change(function(){
				var tmpid = $(this).val();
				$.ajax({
					type : "post",
					url : "../diagnose/getTurbineList.do",
					dataType : "json",
					data : {farmid:tmpid},
					success : function(data){
						var turbineOptionStr = "";
						var turbineList = eval(data.resBody);
						for(var i=0; i<turbineList.length; i++){
							if(i==0)
								turbineOptionStr = "<option value='" + turbineList[i] + "' selected>" + turbineList[i] + "</option>";
							else
								turbineOptionStr = turbineOptionStr + "<option value='" + turbineList[i] + "'>" + turbineList[i] + "</option>";
						}
						$("#turbine").empty();
						$("#turbine").append(turbineOptionStr);
					}
				});
			});
		}
	});
	
	$("#search").click(function(){
		$("#modal").modal({
			keyboard:false,
			backdrop:true//'static'
		});
		$("#modal").empty();
			if (!+[1,]){//IE
				$.fn.spin = function(opts) {
					this.each(function() {
					  var $this = $(this),
						  data = $this.data();
					  if (data.spinner) {
						data.spinner.stop();
						delete data.spinner;
					  }
					  data.spinner = new Spinner($.extend({color: 'white'}, opts)).spin(this);
					});
					return this;
				};
				$("#modal").append("<div id='loading' style='margin-top:" + height/2 + "px;' class='center'></div><div class='center white' style='padding-top:50px;'><span>数据正在查询中，请耐心等待...</span></div>");
				var opts = {
						  lines: 12, // The number of lines to draw
						  length: 10, // The length of each line
						  width: 7, // The line thickness
						  radius: 30, // The radius of the inner circle
						  corners: 1, // Corner roundness (0..1)
						  rotate: 0, // The rotation offset
						  direction: 1, // 1: clockwise, -1: counterclockwise
						  color: '#fff', // #rgb or #rrggbb or array of colors
						  speed: 1, // Rounds per second
						  trail: 60, // Afterglow percentage
						  shadow: true, // Whether to render a shadow
						  hwaccel: false, // Whether to use hardware acceleration
						  className: 'spinner', // The CSS class to assign to the spinner
						  zIndex: 2e9, // The z-index (defaults to 2000000000)
				};
				$('#loading').spin(opts);
		}else{//非IE
			$("#modal").append("<div id='loading' style='margin-top:" + height/2 + "px;'></div><div class='center white'><span>数据正在查询中，请耐心等待...</span></div>");
			$('#loading').shCircleLoader({
				dots: 10,
				radius: 50,
				color: 'white',
			    dotsRadius: 10
			});
		}
		var farmid = $("#farmid option:selected").val();
		var turbine = $("#turbine option:selected").val();
		var startDate = $("#start").val();
		var endDate = $("#end").val();
		$(grid_selector).jqGrid('GridUnload');
		loadGrid(farmid,turbine,startDate,endDate);
	});
	
	function loadGrid(farmid,turbine,startDate,endDate){
		$.ajax({
			type : "post",
			url : "../diagnose/datagrid.do",
			dataType : "json",
			data : {farmid:farmid,turbine:turbine,startDate:startDate,endDate:endDate},
			success : function(data) {
				if (data.status == "SUCCESS") {
					//处理jqGrid
					$("#modal").modal('hide');
					drecordArr = data.resBody;
					$(grid_selector).jqGrid({
						data : drecordArr,
						datatype : "local", // 为local时初始化不加载，支持json，xml等
						colNames : [ '风场代码', '风场名称', '机组号','故障代码','故障描述',"故障时间",'毫秒','风机功率','风速','风机转速','变桨角度' ], // 表头
						colModel : [ // 这里会根据index去解析jsonReader中root对象的属性，填充cell
						 {
							name : 'fcode',
							index : 'fcode',
							key : true,
							width : 50,
							align : "center",
							sortable : true,
							frozen : true,
							editable : false,
						}, {
							name : 'farmname',
							index : 'farmname',
							width : 100,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'wcode',
							index : 'wcode',
							width : 50,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'trigkey',
							index : 'trigkey',
							width : 100,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'desc',
							index : 'desc',
							width : 150,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'times',
							index : 'times',
							width : 150,
							align : "center",
							formatter:'date',
							formatoptions: {srcformat:"ISO8601Long", newformat: 'Y-m-d H:i:s'}, 
							editable : false,
							edittype : "date",
							sortable : false
						}, {
							name : 'msecond',
							index : 'msecond',
							width : 80,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'gpower',
							index : 'gpower',
							width : 100,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'wspeed',
							index : 'wspeed',
							width : 100,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'gspeed',
							index : 'gspeed',
							width : 100,
							align : "center",
							editable : false,
							sortable : false
						}, {
							name : 'pangle',
							index : 'pangle',
							width : 100,
							align : "center",
							editable : false,
							sortable : false
						} ],
						width : 'auto', // 数字 & 'auto','100%'
						height : gridhegith,
						rowNum : 10, // 每页记录数
						rowList : [10,20,30,50,70,100], // 每页记录数可选列表
						pager : pager_selector, // 分页标签divID
						viewrecords : true, // 显示记录数信息，如果这里设置为false,下面的不会显示
						// recordtext: "第{0}到{1}条, 共{2}条记录",
						//默认显示为{0}-{1} 共{2}条 scroll: false,
						//滚动翻页，设置为true时翻页栏将不显示
						sortable : false,//这里是排序的默认设置，这些值会根据列表header点击排序时覆盖
						sortname : "farmid",
						sortorder : "asc",
						altRows : true,
//						prmNames : {  
//						    page:"page",    // 表示请求页码的参数名称  
//						    rows:"rows",    // 表示请求行数的参数名称  
//						    sort: "sidx", // 表示用于排序的列名的参数名称  
//						    order: "sord", // 表示采用的排序方式的参数名称  
//						    search:"_search", // 表示是否是搜索请求的参数名称  
//						    nd:"nd", // 表示已经发送请求的次数的参数名称  
//						    id:"id", // 表示当在编辑数据模块中发送数据时，使用的id的名称  
//						    oper:"oper",    // operation参数名称（我暂时还没用到）  
//						    editoper:"edit", // 当在edit模式中提交数据时，操作的名称  
//						    addoper:"add", // 当在add模式中提交数据时，操作的名称  
//						    deloper:"del", // 当在delete模式中提交数据时，操作的名称  
//						    subgridid:"id", // 当点击以载入数据到子表时，传递的数据名称  
//						    npage: null,   
//						    totalrows:"totalrows" // 表示需从Server得到总共多少行数据的参数名称，参见jqGrid选项中的rowTotal  
//						}
						prmNames : {oper:"oper",editoper:"edit", addoper:"add", deloper:"del"},

						caption : "故障信息列表", // 显示查询结果表格标题
						//rownumbers : true, // 设置列表显示序号,需要注意在colModel中不能使用rn作为index
						//rownumWidth : 30, // 设置显示序号的宽度，默认为25
						multiselect : true, // 多选框
						multiboxonly : true,// 在点击表格row时只支持单选，只有当点击checkbox时才多选，需要multiselect=true是有效
						
						//toolbar : [true,"both"],
						scroll : false,//创建一个动态滚动的表格，当为true时，翻页栏被禁用
						pgbuttons : true,//是否显示翻页按钮
						pginput : true,//是否显示跳转页面的输入框
						pgtext : "第 {0} 页，共 {1} 页",
						emptyrecords : "无故障信息",//当返回的数据行数为0时显示的信息,。只有当属性 viewrecords 设置为ture时起作用
						loadtext : "数据查询中...",//当请求或者排序时所显示的文字内容
						loadComplete : function() {
							var table = this;
							setTimeout(function(){
								updatePagerIcons(table);
							}, 0);
						}
							
					});
					$(window).triggerHandler('resize.jqGrid');// trigger window
					// resize to make
					// the grid get the
					// correct size

					// 这里设定分页bar显示的信息
					$(grid_selector).jqGrid('navGrid', pager_selector, {
						cloneToTop: true,
						edit : false,
						editicon : 'ace-icon fa fa-pencil blue',
						add : false,
						addicon : 'ace-icon fa fa-plus-circle purple',
						del : false,
						delicon : 'ace-icon fa fa-trash-o red',
						delfunc : deleteRowsData,
						search : true,
						searchicon : 'ace-icon fa fa-search orange',
						view : true,
						viewicon : 'ace-icon fa fa-search-plus grey',
						refresh : false
					}, {
						recreateForm: true,
						checkOnSubmit: false, 
						closeAfterEdit: true,
						beforeShowForm : beforeEditCallback,
						afterSubmit : afterEditCallBack
					}, {
						recreateForm: true,
						checkOnSubmit: false, 
						closeAfterAdd: true,
						beforeShowForm : beforeEditCallback,
						afterSubmit : afterAddCallBack
					}, {
//						recreateForm: true,
//						checkOnSubmit: false, 
//						beforeShowForm : beforeDeleteCallback,
//						afterSubmit : afterDeleteRowsCallBack
					},{
						closeAfterSearch: true
					},{},{}
					);
					
				}
			}
		});
	}
	
	//replace icons with FontAwesome icons like above
	function updatePagerIcons(table) {
		var replacement = 
		{
			'ui-icon-seek-first' : 'ace-icon fa fa-angle-double-left bigger-140',
			'ui-icon-seek-prev' : 'ace-icon fa fa-angle-left bigger-140',
			'ui-icon-seek-next' : 'ace-icon fa fa-angle-right bigger-140',
			'ui-icon-seek-end' : 'ace-icon fa fa-angle-double-right bigger-140'
		};
		$('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
			var icon = $(this);
			var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
			
			if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
		});
	}

	
	function beforeDeleteCallback(e) {
		var form = $(e[0]);
		if(form.data('styled')) return false;
		
		form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
		style_delete_form(form);
		
		form.data('styled', true);
	}
	
	function style_delete_form(form) {
		var buttons = form.next().find('.EditButton .fm-button');
		buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
		buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
		buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>');
	}
	
	function afterEditCallBack(response,postdata){
		var json = eval('(' + response.responseText + ')');
		if(json.status == "SUCCESS"){
			selRowId = $(grid_selector).jqGrid('getGridParam','selrow');
			$(grid_selector).jqGrid('setRowData',selRowId,json.resBody);
			updateUserArrAfterEditRow(json.resBody);
			
			popTipInfo('编辑成功');//弹出提示，提示操作是否成功
			return [true,json.message,selRowId];
		}else{
			popTipInfo('编辑失败');
			return [false,json.message];
		}
	}
	
	//当编辑jqgrid的行数据时，同时更新drecordArr的行信息
	function updateUserArrAfterEditRow(userObj){
		for ( var i = 0; i < drecordArr.length; i++) {
			if (drecordArr[i].id == userObj.id) {
				drecordArr.splice(i,i,userObj);
				break;
			}
		}
	}
	
	function afterAddCallBack(response,postdata){
		var json = eval('(' + response.responseText + ')');
		if(json.status == "SUCCESS"){
			rowId = json.resBody.id;
			$(grid_selector).jqGrid('addRowData',rowId,json.resBody,"last");
			drecordArr.push(json.resBody);//jqGrid在新增行数据的时候，同时往js变量drecordArr中新增该数据
			
			popTipInfo('添加成功');
			return [true,json.message,rowId];
		}else{
			popTipInfo('添加失败');
			return [false,json.message];
		}
	}
	
	//只选中一行的时候做删除
	function afterDeleteRowCallBack(response,postdata){
		var json = eval('(' + response.responseText + ')');
		if(json.status == "SUCCESS"){
			selRowId = $(grid_selector).jqGrid('getGridParam','selrow');
			$(grid_selector).jqGrid('delRowData',selRowId);
			updateUserArrAfterDeleteRow(selRowId);
			
			popTipInfo('删除成功');
			return [true,json.message,selRowId];
		}else{
			popTipInfo('删除失败');
			return [false,json.message];
		}
	}
	
	//选中多行的时候做删除
	function afterDeleteRowsCallBack(response,postdata){
		var json = eval('(' + response.responseText + ')');
		if(json.status == "SUCCESS"){
			selRowIds = $(grid_selector).jqGrid('getGridParam','selarrrow');
			for ( var i = 0, j = selRowIds.length; i < j; i++) {   
			    $(grid_selector).jqGrid('delRowData', selRowIds[0]);
			    updateUserArrAfterDeleteRow(selRowIds[0]);
			} 
			popTipInfo('删除成功');
			return [true,json.message,selRowIds];
		}else{
			popTipInfo('删除失败');
			return [false,json.message];
		}
	}
	
	//jqGrid在删除行数据的时候，同时从js变量drecordArr中删除该数据
	function updateUserArrAfterDeleteRow(userId){
		for ( var idx = 0; idx < drecordArr.length; idx++) {
			if (drecordArr[idx].id == userId) {
				drecordArr.splice(idx,1);
				break;
			}
		}
	}
	
	function beforeEditCallback(e) {
		var form = $(e[0]);
		//form.find('#account').attr('readOnly',rowId=='new'?false:true)
		form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />');
		style_edit_form(form);
		
		selId = form.find('#id').val();
		form.find('#account').attr('readOnly',selId==''?false:true);
	}

	function style_edit_form(form) {
		//update buttons classes
		var buttons = form.next().find('.EditButton .fm-button');
		buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
		buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
		buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>');
		
		buttons = form.next().find('.navButton a');
		buttons.find('.ui-icon').hide();
		buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
		buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');		
	}
	
	//由于在删除多个行数据的时候，使用默认方法会导致ID传入到spring报错，只能对多行删除重新定义
	function deleteRowsData(ids){
		//弹出的dialog的title字段允许HTML代码
		$.widget("ui.dialog", $.extend({}, $.ui.dialog.prototype, {
			_title: function(title) {
				var $title = this.options.title || '&nbsp;';
				if( ("title_html" in this.options) && this.options.title_html == true )
					title.html($title);
				else title.text($title);
			}
		}));
		
		//弹出提示框
		$( "#confirmDelete" ).removeClass('hide').dialog({
			resizable: false,
			modal: true,
			title: '<div class="widget-header"><h4 class="smaller"><i class="ace-icon fa fa-exclamation-triangle red"></i></h4></div>',
			title_html: true,
			buttons: [
				{
					html: "<i class='ace-icon fa fa-trash-o bigger-110'></i>&nbsp; 确定",
					"class" : "btn btn-danger btn-xs",
					click: function() {
						$( this ).dialog( "close" );
						$.ajax({
							type : "POST",
							data : "ids="+ids,
							dataType : "json",
							url: "../user/delUsersByIds.do",
							success : function(data) {
								if (data.status == "SUCCESS") {
									var userTemp;
									selRowIds = $(grid_selector).jqGrid('getGridParam','selarrrow');
									//for ( var i = 0, j = selRowIds.length; i < j; i++) {//如果是在界面上删除显示的数据
									for ( var i = 0; i < selRowIds.length; i++) {//如果只是更新界面的删除标记
										//如果在界面上不显示删除标记，则使用下面的语句来控制界面数据的删除
									    //$(grid_selector).jqGrid('delRowData', selRowIds[0]);
									    //updateUserArrAfterDeleteRow(selRowIds[0]);
										
										//如果在界面上显示删除标记，则使用下面的语句来刷新界面的数据即可
										for ( var j = 0; j < drecordArr.length; j++) {
											userTemp = drecordArr[j];
											if (userTemp.id == selRowIds[i]) {
												userTemp.delFlag = 'X';
												$(grid_selector).jqGrid('setRowData',selRowIds[i],userTemp);
												drecordArr[j] = userTemp;
												break;
											}
										}
									} 
									popTipInfo('删除成功');
								}else{
									popTipInfo('删除失败');
								}
							}
						});
					}
				}
				,
				{
					html: "<i class='ace-icon fa fa-times bigger-110'></i>&nbsp; 取消",
					"class" : "btn btn-xs",
					click: function() {
						$( this ).dialog( "close" );
					}
				}
			]
		});
	}
});
